package org.devops

class TemplateGenerator {
    // 生成部署模板
    def generateDeploymentTemplate(script, String controllerType, String imageName, 
                                  String replicas, String fullImageName, 
                                  String containerPort, String namespace) {
        // 根据资源类型选择模板文件
        def templateFile = (controllerType.toLowerCase() == 'statefulset') ? 
            'statefulset-template.yaml' : 'deployment-template.yaml'
        
        // 读取模板内容
        String template = script.readFile(templateFile)
        
        // 定义替换变量
        def replacements = [
            '${imageName}'       : imageName,
            '${replicas}'       : replicas,
            '${FULL_IMAGE_NAME}': fullImageName,
            '${containerPort}'   : containerPort,
            '${k8s_ns}'         : namespace
        ]
        
        // 执行替换
        String yamlContent = replacements.inject(template) { 
            content, entry -> content.replace(entry.key, entry.value) 
        }
        
        // 写入文件
        script.writeFile file: "${script.env.WORKSPACE}/${controllerType}.yaml", 
                        text: yamlContent
    }

    // 生成Service模板
    def generateServiceTemplate(script, String imageName, 
                               String containerPort, String namespace) {
        // 读取模板内容
        String template = script.readFile('svc-template.yaml')
        
        // 定义替换变量
        def replacements = [
            '${imageName}'    : imageName,
            '${containerPort}': containerPort,
            '${k8s_ns}'       : namespace
        ]
        
        // 执行替换
        String svcYaml = replacements.inject(template) { 
            content, entry -> content.replace(entry.key, entry.value) 
        }
        
        // 写入文件
        script.writeFile file: "${script.env.WORKSPACE}/svc.yaml", 
                        text: svcYaml
    }
}